/*
 * @Author: leemr lscmr@qq.com
 * @Date: 2023-12-11 17:42:59
 * @LastEditors: leemr lscmr@qq.com
 * @LastEditTime: 2023-12-26 11:09:53
 * @FilePath: \futures-bill\src\utils\wxshare.ts
 * @Description:
 *
 */
import WeixinJsSdk from 'weixin-js-sdk'
import { isWxEnv } from './util'
import { getShare } from '~/apis'
import { WXSHARECONFIG } from '~/config'

export interface ShareConfig {
  title: string
  desc: string
  link: string
  imgUrl: string
  success?: () => void
}

function setWX(options: WeixinJsSdk.ConfigOptions, shareConfig: ShareConfig) {
  WeixinJsSdk.config(options)
  WeixinJsSdk.showMenuItems({
    menuList: [
      'menuItem:setFont',
      'menuItem:refresh',
      'menuItem:share:appMessage',
      'menuItem:share:timeline',
      'menuItem:share:qq',
      'menuItem:copyUrl',
    ], // 要显示的菜单项，所有menu项见附录3
  })

  WeixinJsSdk.ready(() => {
    WeixinJsSdk.onMenuShareTimeline(shareConfig)
    WeixinJsSdk.onMenuShareAppMessage(shareConfig)
    // WeixinJsSdk.updateAppMessageShareData(shareConfig)
    // WeixinJsSdk.updateTimelineShareData(shareConfig)
  })
}

export function setShare(shareConfig?: any): void {
  if (!isWxEnv()) { // 非微信环境
    return
  }
  getShare().then((res) => {
    const [error ,data] = res;
    if(error||!data){
      return console.log('微信分享接口错误');
    }
    const wxConfig: WeixinJsSdk.ConfigOptions = {
      debug: false,
      appId: data.appId,
      timestamp: data.timestamp,
      nonceStr: data.nonceStr,
      signature: data.signature,
      jsApiList: [
        'updateAppMessageShareData',
        'updateTimelineShareData',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
      ],
    }
    setWX(wxConfig, { ...WXSHARECONFIG, ...shareConfig })
  })
}
